//
//  HKCalendarAndLocalNotificationHandler.m
//  HKTimeKitApp
//
//  Created by huzhaoke1 on 2023/5/20.
//

#import "HKCalendarAndLocalNotificationHandler.h"
#import "HKCommonDefine.h"
#import <UserNotifications/UserNotifications.h>
#import "HKToastView.h"
#import <EventKit/EventKit.h>

@implementation HKCalendarModel

+ (NSDictionary *)mj_replacedKeyFromPropertyName {
    return @{@"des" : @"description"};
}

@end

@interface HKCalendarAndLocalNotificationHandler ()<UNUserNotificationCenterDelegate>

@end

@implementation HKCalendarAndLocalNotificationHandler

- (void)saveCalendarAndPostLocalNotificationWithModel:(HKCalendarModel *)model {
    EKEventStore *eventStore = [[EKEventStore alloc] init];
    __weak typeof(self) weakSelf = self;
    //06.07 使用 requestAccessToEntityType:completion: 方法请求使用用户的日历数据库
    if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
        // 获取访问权限
        [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error || !granted)
                {
                    [[HKToastView sharedToastView] showToast:@"已拒绝，去开启权限"];
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 用户既然允许事件保存到日历，那就去保存吧
                        [weakSelf _saveDataCalendar:eventStore calendarModel:model];
                    });
                }
            });
        }];
    }
}

// 写入日历
- (void)_saveDataCalendar:(EKEventStore *)eventStore  calendarModel:(HKCalendarModel *)calendarModel {
    // 创建事件
    EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
    event.title  = calendarModel.title ;              //  事件标题
    event.notes = calendarModel.des;               //  事件备注
    event.startDate = [NSDate dateWithTimeIntervalSince1970:calendarModel.reminderTime];// 开始时间
    event.endDate   = [NSDate dateWithTimeIntervalSince1970:calendarModel.endTime];  // 结束时间
    
    [event setCalendar:[eventStore defaultCalendarForNewEvents]];
    NSError *err;
    [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
    [self getLocalAuthorizationWithCalendarModel:calendarModel];
}

- (void)getLocalAuthorizationWithCalendarModel:(HKCalendarModel *)calendarModel {
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions: UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!granted) {
                [self showNoticeAlert];
            } else {
                [self localNotificationWithCalendarModel:calendarModel];
            }
        }];
        // 注册远程通知
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
}

- (void)localNotificationWithCalendarModel:(HKCalendarModel *)calendarModel {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    UNMutableNotificationContent *notificationContent = [[UNMutableNotificationContent alloc] init];
    notificationContent.badge = [NSNumber numberWithInt:1];
    notificationContent.title = calendarModel.title;
    notificationContent.body = calendarModel.des;
    notificationContent.sound = [UNNotificationSound defaultSound];
    notificationContent.categoryIdentifier = @"categoryIdentifier";

    NSDate *beforeDate = [NSDate dateWithTimeIntervalSince1970:calendarModel.reminderTime];
    NSDate *sendDate = [NSDate dateWithTimeInterval:5 * 60 sinceDate:beforeDate];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond  fromDate:sendDate];
    
    UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
    
    UNNotificationRequest *notificationRequest = [UNNotificationRequest requestWithIdentifier:@"request1" content:notificationContent trigger:trigger];
    [center addNotificationRequest:notificationRequest withCompletionHandler:^(NSError * _Nullable error) {
    }];
}

//App在前台时候回调：用户正在使用状态
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}

// 推送消息回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
{
    if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    } else {
       // 本地消息处理
    }
    completionHandler();
}

- (void)showNoticeAlert {
    [[HKToastView sharedToastView] showToast:@"请授权通知权限才能收到通知"];
}

@end
